//
//  KForgotViewController.m
//  Keping
//
//  Created by 柯平 on 2017/6/24.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KForgotViewController.h"
#import "KTextCell.h"
#import "KVeritifyCodeCell.h"
#import "KRequestData.h"
#import "KForgetRequest.h"
#import "KCodeRequest.h"

@interface KForgotViewController ()
{
    NSArray* items;
}
@property(nonatomic,strong)UILabel* forgetLabel;
@property(nonatomic,strong)UIButton* retrieveBtn;
@property(nonatomic,copy)NSString* phone;
@property(nonatomic,copy)NSString* comfirePwd;
@property(nonatomic,copy)NSString* passWord;
@property(nonatomic,copy)NSString* smsCode;

@end

@implementation KForgotViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
    self.whiteNaviBar.hidden = NO;
    [self.view bringSubviewToFront:self.whiteNaviBar];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    items = @[@"Phone",@"Enter Veritification Code",@"Password",@"Confirm Password"];
    
    self.tableView.refreshEnable = NO;
    self.tableView.loadmoreEnable = NO;
    self.tableView.rowHeight = 44;
    [self.view addSubview:self.tableView];
    self.view.backgroundColor = [UIColor whiteColor];
    
}

#pragma mark - Network
-(void)requestCode{
    KCodeRequest* codeRequest = [[KCodeRequest alloc] initWithPhone:self.phone];
    codeRequest.params = @{@"phone":self.phone};
    [codeRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        KRequestData* data = [KRequestData modelWithJSON:request.responseData];
        if (data.statusCode == 200) {
            [self showSuccess:@"验证码已发送！"];
        }else{
            [self showErrorText:data.msg errCode:data.statusCode];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [self showErrorText:@"发送失败！"];
    }];
}

-(void)findPwdAction
{
    if (![self.phone isNotBlank]) {
        [self showErrorText:@"手机号不能为空"];
        return;
    }
    if (![self.smsCode isNotBlank]) {
        [self showErrorText:@"验证码不能为空"];
        return;
    }
    if (![self.passWord isNotBlank]) {
        [self showErrorText:@"密码不能为空"];
        return;
    }
    if (![self.comfirePwd isNotBlank]) {
        [self showErrorText:@"确认密码不能为空"];
        return;
    }
    if (![self.comfirePwd isEqualToString:self.passWord]) {
        [self showErrorText:@"两次输入密码不一致！"];
        return;
    }

    KForgetRequest* request = [[KForgetRequest alloc] init];
    request.params = [NSDictionary dictionaryWithObjectsAndKeys:self.phone,@"phone",[self.passWord md5String],@"passWord",[self.comfirePwd md5String],@"comfirePwd",self.smsCode,@"smsCode", nil];
    [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        KRequestData* data = [KRequestData modelWithJSON:request.responseData];
        if (data.statusCode == 200) {
            [self showSuccess:@"Reset password success！"];
            if ([KAppConfig sharedConfig].isRememberPassword) {
                [[KAppConfig sharedConfig] setPassword:self.comfirePwd];
            }
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [self showErrorText:data.msg errCode:data.statusCode];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [self showErrorText:@"Reset failed!"];
    }];
    
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    [self.forgetLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(84);
        make.height.mas_equalTo(54);
        make.left.right.mas_equalTo(0);
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.top.mas_equalTo(self.forgetLabel.mas_bottom);
        make.right.mas_equalTo(-20);
        make.height.mas_equalTo(items.count*55);
    }];
    [self.retrieveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(-10);
        make.height.mas_equalTo(39);
        make.top.mas_equalTo(self.tableView.mas_bottom).offset(20);
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return items.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    @weakify(self);
    NSString* placeholder = items[indexPath.row];
    if ([placeholder isEqualToString:@"Enter Veritification Code"]) {
        KVeritifyCodeCell* cell = [tableView dequeueReusableCellWithIdentifier:[KVeritifyCodeCell className]];
        if (!cell) {
            cell = [[KVeritifyCodeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[KVeritifyCodeCell className]];
        }
        cell.textTf.placeholder = items[indexPath.row];
        if ([@"passWord" isEqualToString:placeholder] || [@"Confirm Password" isEqualToString:placeholder]) {
            cell.textTf.secureTextEntry = YES;
        }
        [cell.codeBtn setTitle:@"Get Veritification Code" forState:UIControlStateNormal];
        cell.codeBtn.layer.cornerRadius = 19.5;

        cell.buttonBlock = ^{
            if (![weak_self.phone isNotBlank]) {
                [weak_self showErrorText:@"手机号码不能为空！"];
                return;
            }else{
                [weak_self requestCode];
            }
        };
        cell.codeBlock = ^(NSString *text) {
            if ([text isNotBlank]) {
                weak_self.smsCode = text;
            }
        };
        return cell;
    }else{
        KTextCell* cell = [tableView dequeueReusableCellWithIdentifier:[KTextCell className]];
        if (!cell) {
            cell = [[KTextCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[KTextCell className]];
        }
        cell.textTf.placeholder = items[indexPath.row];
        //@[@"Phone",@"Enter Veritification Code",@"Password",@"Confirm Password"]
        cell.textBlock = ^(NSString *text) {
            if ([@"Phone" isEqualToString:placeholder]) {
                weak_self.phone = text;
            }else if ([@"Password" isEqualToString:placeholder]){
                weak_self.passWord = text;
            }else if ([@"Confirm Password" isEqualToString:placeholder]){
                weak_self.comfirePwd = text;
            }
        };
        return cell;
    }
    return nil;
}

-(UILabel *)forgetLabel
{
    if (!_forgetLabel) {
        _forgetLabel = [UILabel new];
        _forgetLabel = [[UILabel alloc]init];
        _forgetLabel.text = @"Forget Password";
        [_forgetLabel sizeToFit];
        _forgetLabel.textAlignment = NSTextAlignmentCenter;
        _forgetLabel.textColor = [UIColor colorWithHexString:@"714FFA"];
        _forgetLabel.font = [UIFont boldSystemFontOfSize:32];
        [self.view addSubview:_forgetLabel];
    }
    return _forgetLabel;
}

-(UIButton *)retrieveBtn
{
    if (!_retrieveBtn) {
        _retrieveBtn = [UIButton commonButtonWithTitle:@"Retrieve Password"];
        _retrieveBtn.layer.cornerRadius = 19.5;
        [_retrieveBtn addTarget:self action:@selector(findPwdAction) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_retrieveBtn];
    }
    return _retrieveBtn;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
